//
//  MineVC.swift
//  MM2
//
//  Created by 李成明 on 2021/12/31.
//

import UIKit
import Kingfisher

private class NavBarView: UIView {
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        addsubViews([titleLabel, settingImg, backIcon])
        backIcon.frame = CGRect(x: 16, y: 8, width: 28, height: 28)
        titleLabel.snp.makeConstraints { make in
            make.edges.equalTo(self)
        }
        
        settingImg.snp.makeConstraints { make in
            make.right.equalTo(self).offset(-16 - 24)
            make.centerY.equalTo(self)
            make.size.equalTo(CGSize(width: 24, height: 24))
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private var outLogin: (() -> Void)?
    private var backClosure: (() -> Void)?
    var title: String = "" {
        didSet {
            titleLabel.text = title
        }
    }
    
    lazy var backIcon: UIImageView = {
        let view = UIImageView()
        view.image = UIImage(named: "fanhui")
        
        view.isUserInteractionEnabled = true
        let tap = UITapGestureRecognizer.init(target: self, action: #selector(backAction))
        view.addGestureRecognizer(tap)
        return view
    }()
    
    private lazy var titleLabel: UILabel = {
        let view = UILabel()
        view.font = UIFont(name: "Verdana", size: 18)
        view.textAlignment = .center
        view.text = User.share.userName
        return view
    }()
    
    private lazy var settingImg: UIImageView = {
        let view = UIImageView()
        view.image = UIImage(named: "mine_setting_icon")
        
        view.isUserInteractionEnabled = true
        let tpa = UITapGestureRecognizer(target: self, action: #selector(outLoginAction))
        view.addGestureRecognizer(tpa)
        
        return view
    }()
    
    @objc private func backAction() {
        backClosure?()
    }
    
    @objc private func outLoginAction() {
        outLogin?()
    }
    
    @discardableResult
    func outLogin(_ closure: (() -> Void)?) -> NavBarView{
        outLogin = closure
        return self
    }
    
    @discardableResult
    func back(_ closure: (() -> Void)?) -> NavBarView{
        backClosure = closure
        return self
    }
}

private class ItemView: UIView {
    
    private lazy var numLabel: UILabel = {
        let view = UILabel()
        view.font = UIFont(name: "Baskerville-Italic", size: 80)
//        view.font = .systemFont(ofSize: 89, weight: .ultraLight)
        view.textAlignment = .center
        return view
    }()
    
    private lazy var titleLabel: UILabel = {
        let view = UILabel()
        view.font = UIFont(name: "Helvetica-BoldOblique", size: 14)
        view.textAlignment = .center
        return view
    }()
    
    var viewHeight = 100.0
    var viewWidth = 80.0
    var titleStr: String = "" {
        didSet {
            titleLabel.text = titleStr
        }
    }
    
    var numValue: Int = 0 {
        didSet {
            numLabel.text = "\(numValue)"
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        addsubViews([numLabel, titleLabel])
        numLabel.snp.makeConstraints { make in
            make.left.bottom.top.equalTo(self)
            make.right.equalTo(titleLabel.snp.left).offset(10)
        }
        
        titleLabel.snp.makeConstraints { make in
            make.bottom.right.equalTo(self)
            make.width.equalTo(40)
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

class MineVC: MViewController {

    init(userId: Int = User.share.userId, hideTabbar: Bool = false) {
        super.init(nibName: nil, bundle: nil)
        self.userId = userId
        self.hideTabbar = hideTabbar
        self.navBar.backIcon.isHidden = !hideTabbar
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        setupUI()
        
        requestFollowNum()
        dailyListView.beginRequest()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        if !hideTabbar {
            (self.tabBarController as? MTabBarController)?.showTababr()
        }
        
        self.requestFollowNum()
    }
    
    private var hideTabbar = true
    private var userId: Int = User.share.userId
    private var user: User = User() {
        didSet {
            followItem.numValue = user.followNum
            fansItem.numValue = user.fansNum
            avatar.setAvatar(urlStr: user.avatar)
            navBar.title = user.userName
        }
    }
    
    private lazy var avatar: UIImageView = {
        let view = UIImageView()
        view.layer.masksToBounds = true
        view.layer.cornerRadius = 30
        view.setAvatar(urlStr: User.share.avatar)
        view.contentMode = .scaleAspectFit
        return view
    }()
    
    private lazy var faceValueLabel: UILabel = {
        let view = UILabel()
//        view.font = UIFont(name: "Verdana-Italic", size: 50, weight: .ultraLight)
        view.font = .systemFont(ofSize: 50, weight: .ultraLight)
        view.textColor = .initWithRGB(135, 206, 250)
        return view
    }()
    
    private lazy var followItem: ItemView = {
        let view = ItemView(frame: CGRect.zero)
        view.titleStr = "关注"
        view.numValue = 0
        return view
    }()
    
    private lazy var fansItem: ItemView = {
        let view = ItemView(frame: CGRect.zero)
        view.titleStr = "粉丝"
        view.numValue = 0
        return view
    }()
    
    private lazy var navBar: NavBarView = {
        let view = NavBarView(frame: CGRect(x: 0, y: kStateBarHeight, width: kScreenWidth, height: kNaviBarHeight))
        view.back { [weak self] in
            self?.navigationController?.popViewController(animated: true)
        }.outLogin { [weak self] in
            UserDefaults.standard.set(nil, forKey: defaultUserKey)
            let window = UIApplication.shared.keyWindow
            window?.rootViewController = MNavigationController(rootViewController: LoginVC())
        }
        return view
    }()
    
    private lazy var greyLine: UIView = {
        let view = UIView()
        view.backgroundColor = mainColor
        return view
    }()
    
    private lazy var dailyTitle: UILabel = {
        let view = UILabel()
        view.text = "  动态"
        
        let line = UIView()
        view.addSubview(line)
        line.backgroundColor = mainColor
        line.alpha = 0.3
        line.snp.makeConstraints { make in
            make.left.right.bottom.equalTo(view)
            make.height.equalTo(0.3)
        }
        return view
    }()
    
    private lazy var dailyListView: DailyListView = {
        let view = DailyListView(frame: CGRect.zero)
        view.listType = .personal(userId: userId)
        view.fatherVC = self
        return view
    }()
}

extension MineVC {
    private func setupUI() {
//        view.backgroundColor = .initWithRGB(230, 230, 230)
        view.addsubViews([navBar, avatar, followItem, fansItem, greyLine, dailyTitle, dailyListView])
        navBar.frame = CGRect(x: 0, y: kStateBarHeight, width: kScreenWidth, height: kNaviBarHeight)
        
        var y = kStateAndNavH + 20
        avatar.frame = CGRect(x: 16, y: y, width: 60, height: 60)
        
        let itemWidth = followItem.viewWidth
        let itemHeight = followItem.viewHeight
        
        var x: CGFloat = 16 + 60 + 40
        followItem.frame = CGRect(x: x, y: kStateAndNavH, width: itemWidth, height: itemHeight)
        x += (itemWidth + 20)
        fansItem.frame = CGRect(x: x, y: kStateAndNavH, width: itemWidth, height: itemHeight)
        y += itemHeight
        
        greyLine.frame = CGRect(x: 0, y: y+1, width: kScreenWidth, height: 0.3)
        dailyTitle.frame = CGRect(x: 0, y: y, width: kScreenWidth, height: 50)
        y += 50
        
        dailyListView.frame = CGRect(x: 0, y: y, width: kScreenWidth, height: kScreenHeight - y)
    }
    
    private func requestFollowNum() {
        MoyaNetwork.request(target: BaseApi.followAndFansNum(userId: userId)) { json, jsonStr in
            guard let user = User.deserialize(from: json["data"].dictionaryObject) else { return }
            self.user = user
        }
    }
}
